import {Modal,Message} from 'iview';
import service from "./request";
import qs from 'qs'

export let WS_BASE_URL = 'wss://chenborui.xyz:5443/ws'
// export let WS_BASE_URL = 'wss://localhost:5443/ws'

/**
 * 日期转为字符串
 *
 * @param d 日期
 * @returns {*}
 */
export function dateToString(d){
    let date = new Date(d)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

/**
 * 展示日期 (2020-06-01T19:43:23.000+0000 -> yy-mm-dd hh:MM:ss)
 *
 * @param d 日期
 * @returns {*}
 */
export function showDate(d){
    let arr = d.split('T')
    return arr[0] + ' ' + arr[1].substring(0,8)
}

/**
 * 手机号检查
 * @param value
 * @returns {string}
 */
export function judgePhone(value) {
    var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[4-9]{1})|(18[0-9]{1})|(199))+\d{8})$/;
    if (value === '') {
        return  "手机号码不能为空！"
    } else if (value.length !== 11) {
        return  "请输入11位手机号码！"
    } else if (!myreg.test(value)) {
        return "请输入有效的手机号码！"
    }
    return ''
}

export function downloadExcel(res) {
    const blob = new Blob([res.data],
        { type: 'application/vnd.ms-excel;charset=utf-8' });
    let disposition = res.headers['content-disposition']
    let filename = decodeURIComponent(disposition.split('=')[1]);
    if ('download' in document.createElement('a')) {
        const downloadElement = document.createElement('a');
        let href = '';
        if(window.URL) href = window.URL.createObjectURL(blob);
        else href = window.webkitURL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = filename;
        document.body.appendChild(downloadElement);
        downloadElement.click();
        if(window.URL) window.URL.revokeObjectURL(href);
        else window.webkitURL.revokeObjectURL(href);
        document.body.removeChild(downloadElement);
    } else {
        navigator.msSaveBlob(blob, filename);
    }
}

export function exportExcel(url,ids){
    let content = ids.length === 0 ? '确定要导出所有的数据？或者去勾选数据项？' : '确定要导出所勾选的数据项？'
    Modal.confirm({
        title: '提醒',
        content: content,
        onOk: () => {
            service({
                url: url,
                method: 'get',
                responseType: 'blob',
                params: {ids: ids},
                paramsSerializer: params => {
                    return qs.stringify(params, {indices: false})
                }
            }).then(res => {
                downloadExcel(res);
            })
        },
        onCancel: () => {
            Message.info('已取消');
        }
    });
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result

    const later = function() {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp

        // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
            if (!immediate) {
                result = func.apply(context, args)
                if (!timeout) context = args = null
            }
        }
    }

    return function(...args) {
        context = this
        timestamp = +new Date()
        const callNow = immediate && !timeout
        // 如果延时不存在，重新设定延时
        if (!timeout) timeout = setTimeout(later, wait)
        if (callNow) {
            result = func.apply(context, args)
            context = args = null
        }

        return result
    }
}